package org.linlinjava.litemall.wx.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.UncDate;
import org.linlinjava.litemall.db.domain.LitemallRedPacaketsHistory;
import org.linlinjava.litemall.db.po.CutpriceSixPo;
import org.linlinjava.litemall.db.po.OrderDetailPo;
import org.linlinjava.litemall.db.util.APIUtil;

import org.linlinjava.litemall.wx.vo.wechart.TemplateData;
import org.linlinjava.litemall.wx.vo.wechart.WechatNewTemplateVo;
import org.linlinjava.litemall.wx.vo.wechart.WechatTemplateVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


/**
 * 
 * @author caiy
 * 2019/4/18
 *
 */
public class WechatPushOneUserUtils {

	private final Log log = LogFactory.getLog(WechatPushOneUserUtils.class);
//	 private static String AppId = GlobalValue.wxSubAppId;
//	 private static String secret = GlobalValue.wxSecret;
	/**
	 * 发送订阅消息入口
	 *
	 * */
	public  static  JSONObject newsend(LitemallRedPacaketsHistory spfc, CutpriceSixPo cutpriceSixPo, String wechatTemplateCode, String access_token, int flag, String userId) throws Exception{
		WechatPushOneUserUtils wechatPush = new WechatPushOneUserUtils();
	//	log.info(" spfc"+spfc+" wechatTemplateCode "+wechatTemplateCode+" access_token " +access_token+" flag"+flag);
		JSONObject json = wechatPush.sendTemplateNewMessage( spfc,cutpriceSixPo,wechatTemplateCode,access_token,flag,userId);
		return json;
	}
	/**
	 * 发送订阅消息处理函数
	 * */
	public  JSONObject sendTemplateNewMessage(  LitemallRedPacaketsHistory userItemListPo, CutpriceSixPo cutpriceSixPo, String wechatTemplateCode, String access_token, int flag, String userId) {
		//String access_token = qrController.getAccess_token();
		log.info("sendNewTemplateMessage");
		try {
			Map<String, TemplateData> map = new HashMap<>();
			if(flag==3){
				///cutpriceModel为3时候发送订阅消息
				if (StringUtils.isNotBlank(userItemListPo.getTitle())) {//活动名称
					map.put("thing1", new TemplateData(userItemListPo.getTitle()));
				} else {
					map.put("thing1", new TemplateData("板尚商城"));
				}
				if (userItemListPo.getPrice()!=0) {//砍价金额
					double price = (double)userItemListPo.getPrice()/100;
					map.put("thing2", new TemplateData(price+"元现金红包"));
				} else {
					map.put("thing2", new TemplateData(""));
				}

				Date date = new Date();
				String str = "yyyy-MM-dd HH:mm";
				SimpleDateFormat sdf = new SimpleDateFormat(str);
				map.put("date3", new TemplateData(sdf.format(date)));
			}
			log.info("map: "+map);
			WechatNewTemplateVo sendTemplateMessage = new WechatNewTemplateVo();
			//拼接数据
			//sendTemplateMessage.setTouser(userItemListPo.getUserId());
			sendTemplateMessage.setTemplate_id(wechatTemplateCode);
			/*if(flag!=3 && flag!=4){
				sendTemplateMessage.setTouser(orderdetail.getUserId());
				sendTemplateMessage.setPage("pages/index/index");
			}else if(flag==4){
				sendTemplateMessage.setTouser(userId);
				if (cutpriceSixPo!=null)
					sendTemplateMessage.setPage("pages/OneInMillion/OneInMillion?activityId="+cutpriceSixPo.getActivityListId()+"&cutpriceId="+cutpriceSixPo.getId()+"&share=true");
				else
					sendTemplateMessage.setPage("/pages/pingT/pingT?platformCutpriceId="+userItemListPo.getId()+"&createTime="+Timestamp.valueOf(userItemListPo.getCreateTime()).getTime()+"&share=true");
			} else{*/
				sendTemplateMessage.setTouser(userItemListPo.getUserId());
				sendTemplateMessage.setPage("/pages/index/index?cutpriceId="+userItemListPo.getId()+"&share=true&scene=1008");
			//}
			//sendTemplateMessage.setForm_id(formId);
			sendTemplateMessage.setData(map);
			log.info("sendTemplateMessage:"+sendTemplateMessage);
			String json =  JSONObject.toJSONString(sendTemplateMessage);
			String ret = this.sendPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token, json);
			log.info("##订阅消息JSON数据:  "+json+",ret:"+ret);
			return JSON.parseObject(ret);
		} catch (Exception e) {
			log.info(e);
			return  JSON.parseObject("error");
		}
	}



	/**
	 *
	 * 发送模板消息入口, 即将废弃
	 * **/
	 public  static  JSONObject send(String formId, OrderDetailPo orderdetail, LitemallRedPacaketsHistory spfc, CutpriceSixPo cutpriceSixPo, String wechatTemplateCode, String access_token, int flag, String userId) throws Exception{
		 WechatPushOneUserUtils wechatPush = new WechatPushOneUserUtils();
		// log.info("formId:"+formId+"orderdetail:"+orderdetail+" spfc"+spfc+" wechatTemplateCode "+wechatTemplateCode+" access_token " +access_token+" flag"+flag);
		 JSONObject json = wechatPush.sendTemplateMessage(formId, orderdetail, spfc,cutpriceSixPo,wechatTemplateCode,access_token,flag,userId);
		 return json;
	 }

	/**
     * 	发送模板消息sendTemplateMessage
     * 	小程序模板消息,发送服务通知
     * @param formId
     * @param orderdetail
     * @param userItemListPo
	 * @param wechatTemplateCode
	 * @return
     */
    public  JSONObject sendTemplateMessage(String formId, OrderDetailPo orderdetail, LitemallRedPacaketsHistory userItemListPo, CutpriceSixPo cutpriceSixPo, String wechatTemplateCode, String access_token, int flag, String userId) {
    	//String access_token = qrController.getAccess_token();
      log.info("sendTemplateMessage");
    	try {
			Map<String, TemplateData> map = new HashMap<>();
			//下单通知
			if(flag==1) {
				if(StringUtils.isNotBlank(orderdetail.getTakeFoodCode())) {
					  map.put("keyword1",new TemplateData(orderdetail.getTakeFoodCode()));
				}else {
					  map.put("keyword1",new TemplateData(""));
				}
				if(StringUtils.isNotBlank(orderdetail.getStoreName())) {
					map.put("keyword2",new TemplateData(orderdetail.getStoreName()));
				}else {
				    map.put("keyword2",new TemplateData(""));
				}
				if(StringUtils.isNotBlank(orderdetail.getAddress())) {
					map.put("keyword3",new TemplateData(orderdetail.getAddress()));
				}else {
					  map.put("keyword3",new TemplateData(""));
				}
				if(orderdetail.getPaytime()!=null) {
					map.put("keyword4",new TemplateData(UncDate.timeStampToDate(orderdetail.getPaytime())));
				}else {
				    map.put("keyword4",new TemplateData(UncDate.timeStampToDate(System.currentTimeMillis())));
				}
					map.put("keyword5",new TemplateData("恭喜你，下单成功，请耐心等待，让美味飞一会儿！"));
			//上菜通知
    		}else if(flag==2){
    			if(StringUtils.isNotBlank(orderdetail.getTakeFoodCode())) {//取餐码
					  map.put("keyword1",new TemplateData(orderdetail.getTakeFoodCode()));
				}else {
					  map.put("keyword1",new TemplateData(""));
				}
				if(StringUtils.isNotBlank(orderdetail.getDeskId())) {//桌台号
					map.put("keyword2",new TemplateData(orderdetail.getDeskId()));
				}else {
				    map.put("keyword2",new TemplateData(""));
				}
				if(StringUtils.isNotBlank(orderdetail.getStoreName())) {//店铺名称
					map.put("keyword3",new TemplateData(orderdetail.getStoreName()));
				}else {
					  map.put("keyword3",new TemplateData(""));
				}
				if(StringUtils.isNotBlank(orderdetail.getSumprice().toString())) {//订单总金额
					//处理订单总金额
					String price = APIUtil.doubleToString(orderdetail.getSumprice(), 100L)+"元";
					map.put("keyword4",new TemplateData(price));
				}else {
					  map.put("keyword4",new TemplateData(""));
				}
				if(orderdetail.getPaytime()!=null) {//点餐时间
					map.put("keyword5",new TemplateData(UncDate.timeStampToDate(orderdetail.getPaytime())));
				}else {
				    map.put("keyword5",new TemplateData(UncDate.timeStampToDate(System.currentTimeMillis())));
				}
				map.put("keyword6",new TemplateData("您的餐点已就绪，请您尽快取餐"));
    		}else if(flag==3){
        if (StringUtils.isNotBlank(userItemListPo.getTitle())) {//活动名称
          map.put("keyword1", new TemplateData(userItemListPo.getTitle()));
        } else {
          map.put("keyword1", new TemplateData(""));
        }
        if (userItemListPo.getPrice()!=0) {//砍价金额
          double price = (double)userItemListPo.getPrice()/100;
          map.put("keyword2", new TemplateData(price+"元现金红包"));
        } else {
          map.put("keyword2", new TemplateData(""));
        }
        map.put("keyword3", new TemplateData("待领取"));
      }else if(flag==4){
			  if(cutpriceSixPo!=null) {
          if (StringUtils.isNotBlank(cutpriceSixPo.getTitle())) {//活动名称
            map.put("keyword1", new TemplateData(cutpriceSixPo.getTitle()));
          } else {
            map.put("keyword1", new TemplateData(""));
          }
        }else{
          if (StringUtils.isNotBlank(userItemListPo.getTitle())) {//活动名称
            map.put("keyword1", new TemplateData(userItemListPo.getTitle()));
          } else {
            map.put("keyword1", new TemplateData(""));
          }

        }
        //if (cutpriceSixPo.getPrice()!=0) {//砍价金额
          //double price = (double)cutpriceSixPo.getPrice()/100;
          map.put("keyword2", new TemplateData("随机"));
      //  } else {
       //   map.put("keyword2", new TemplateData(""));
       // }
        map.put("keyword3", new TemplateData("待领取"));
      }
			log.info("map: "+map);
			WechatTemplateVo sendTemplateMessage = new WechatTemplateVo();
			//拼接数据
			//sendTemplateMessage.setTouser(userItemListPo.getUserId());
			sendTemplateMessage.setTemplate_id(wechatTemplateCode);
			if(flag!=3 && flag!=4){
        sendTemplateMessage.setTouser(orderdetail.getUserId());
        sendTemplateMessage.setPage("pages/index/index");
      }else if(flag==4){
        sendTemplateMessage.setTouser(userId);
        if (cutpriceSixPo!=null)
          sendTemplateMessage.setPage("pages/OneInMillion/OneInMillion?activityId="+cutpriceSixPo.getActivityListId()+"&cutpriceId="+cutpriceSixPo.getId()+"&share=true");
        else
          sendTemplateMessage.setPage("/pages/pingT/pingT?platformCutpriceId="+userItemListPo.getId()+"&createTime="+Timestamp.valueOf(userItemListPo.getCreateTime()).getTime()+"&share=true");
      } else{
        sendTemplateMessage.setTouser(userItemListPo.getUserId());
        sendTemplateMessage.setPage("/pages/pingT/pingT?platformCutpriceId="+userItemListPo.getId()+"&createTime="+ Timestamp.valueOf(userItemListPo.getCreateTime()).getTime()+"&share=true");
      }

			//sendTemplateMessage.setPage("pages/allOrders/allOrders?userId="+orderdetail.getUserId()+"&types=0");
			sendTemplateMessage.setForm_id(formId);
			sendTemplateMessage.setData(map);
			//sendTemplateMessage.setEmphasis_keyword("");
        log.info("sendTemplateMessage:"+sendTemplateMessage);
			String json =  JSONObject.toJSONString(sendTemplateMessage);
			
			String ret = this.sendPost("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+access_token, json);
			log.info("##模版发送JSON数据:  "+json+",ret:"+ret);
			return JSON.parseObject(ret);
		} catch (Exception e) {
			log.info(e);
			return  JSON.parseObject("error");
		}
    }
    /**
     * 	发送post请求 json格式
     * @param url
     * @param param
     * @return
     */
    public String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // System.out.println("发送 POST 请求出现异常!"+e);
            // e.printStackTrace();
          log.info(e);
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
	public static void main(String[] args) {
		WechatPushOneUserUtils s = new WechatPushOneUserUtils();
       // JSONObject js = s.sendTemplateNewMessage("ohKTy5Mj93jc0vpZXL6s6TcYYTnc", "of30Baq8NYYfilvV_hSzc9IA4yUnFl5i2xIWPuBJOow", "", "da6e00b8fa0a449fa40697ce3e6c47fc");
       // System.out.println(js);
		
		//s.pushOneUser("",null, "");
	}
}
